package com.ls.commons.schedule.quartz;

import java.lang.reflect.Method;

import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ls.commons.schedule.exception.MyScheduleException;
import com.ls.fw.commons.spring.SpringContextHolder;

/**
 * 
 * @author  sheng.li
 * @version  [版本号, 2015年6月29日]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
@DisallowConcurrentExecution
public class JobSyncFactory implements Job {
    private static final Logger logger = LoggerFactory.getLogger(JobSyncFactory.class);
    
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDataMap dataMap = context.getMergedJobDataMap();
        String factoryType = dataMap.getString("Job_Param_factoryType");
        String target = dataMap.getString("Job_Param_target");
        String method = dataMap.getString("Job_Param_method");
        Class<?> clazz = null;
        Object object = null;
        try {
            if(factoryType.equals("new")) {
                clazz = Class.forName(target);
                object = clazz.newInstance();
            }else {
                if(SpringContextHolder.containsBean(target)) {
                    object = SpringContextHolder.getBean(target);
                }else {
                    object = SpringContextHolder.getBean(Class.forName(target));
                }
                if(object == null) {
                    throw new MyScheduleException("JobSyncFactory从Spring容器中无法获取目标执行类!");
                }
                clazz = object.getClass();
            }
            Method m = clazz.getDeclaredMethod(method);
            m.invoke(object);
        } catch(Exception e) {
            logger.error("JobSyncFactory执行错误!",e);
        }
    }
}
